package com.lemon.components.ant.util.sqlparser;

import java.util.List;

import org.assertj.core.util.Lists;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLExpr;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.expr.SQLBinaryOpExpr;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlExportParameterVisitor;
import com.alibaba.druid.util.JdbcConstants;

import lombok.experimental.UtilityClass;

@UtilityClass
public class WhereParser {

	public List<SQLBinaryOpExpr> parse(String sql) {
		List<SQLBinaryOpExpr> list = Lists.newArrayList();
		List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.MYSQL);
		if (!sql.isEmpty()) {
			SQLStatement sqlStatement = statementList.get(0);
			if (sqlStatement instanceof SQLSelectStatement) {
				SQLSelectStatement selectStatement = (SQLSelectStatement) sqlStatement;
				SQLExpr where = selectStatement.getSelect().getQueryBlock().getWhere();
				if (where != null) {
					where.accept(new MySqlExportParameterVisitor() {
						@Override
						public boolean visit(SQLBinaryOpExpr x) {
							if (x.getLeft().getChildren().size() == 1) {
								list.add(x);
							}
							return super.visit(x);
						}

					});
				}
			}
		}
		return list;
	}
}
